<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="系统配置项设置" name="first" />
      <el-tab-pane label="总入口配置" name="second" />
      <el-tab-pane label="OCR识别设置" name="ocr" />
    </el-tabs>
    <template v-if="activeName === 'first'">
      <div class="formBox">
        <el-form label-width="200px">
          <el-form-item v-for="(item, index) in systemList" :key="index" :label="item.configName">
            <el-input v-model="item.configValue" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div class="footerForm">
          <el-button type="primary" v-hasPermi="['system:config:update']" class="add"
            @click="updateSystemData">确定</el-button>
          <el-button class="delBtn">取消</el-button>
        </div>
      </div>
    </template>
    <template v-if="activeName==='second'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['bus:busConfig:add']" type="primary" plain icon="el-icon-plus" class="add"
            @click="handleAdd">新增</el-button>
        </el-col>
        <right-toolbar :show-search.sync="showSearch" @queryTable="getListData" />
      </el-row>
      <el-table ref="table" :key="tableKey" v-loading="loading" :data="roleList" style="margin-top: 20px">
        <el-table-column label="名称" prop="title" width="120" />
        <el-table-column label="标签" prop="tag" width="150" />
        <el-table-column label="内容" prop="content" width="150" />
        <el-table-column label="图片" width="150" align="center">
          <template slot-scope="scope">
            <img :src="'/api' + scope.row.imgUrl" alt="" class="img" />
          </template>
        </el-table-column>
        <el-table-column label="路径" prop="pageUrl" width="150" />
        <el-table-column label="状态" align="center" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_setting_state" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-hasPermi="['bus:busConfig:query']" type="text" class="btnText"
              @click="handleUpdate(scope.row)">管理</el-button>
            <el-button v-hasPermi="['bus:busConfig:remove']" class="btnText" type="text"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getListData" />
    </template>
    <template v-if="activeName === 'ocr'">
      <div class="ocrBox">
        <div class="item-box">
          <div class="left">OCR识别字段</div>
          <div class="right">可匹配字段</div>
        </div>
        <div class="item-box" v-for="(item,index) in ocrList" :key="index">
          <div class="left">{{item.configName}}</div>
          <div class="right"><el-input class="ipt" v-model="item.configValue" placeholder="请输入"></el-input></div>
        </div>
        <div class="item-box">
          <div class="left"></div>
          <div class="right">
            <el-button type="primary" v-hasPermi="['system:config:update']" @click="updateOcrData()" class="add">确定</el-button>
            <el-button class="delBtn">取消</el-button>
          </div>
        </div>
      </div>
    </template>
    <el-dialog :title="title" :visible.sync="open" width="786px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-position="top">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="名称" prop="title">
              <el-input v-model="addForm.title" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tag">
              <el-input v-model="addForm.tag" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="内容" prop="content">
              <el-input v-model="addForm.content" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路径" prop="pageUrl">
              <el-input v-model="addForm.pageUrl" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="addForm.status" active-value="1" inactive-value="0" active-color="#0052d9" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item prop="imgUrl">
              <span slot="label"> 图片 </span>
              <el-upload class="upload-demo" :action="uploadUrl" :before-upload="handleBeforeUpload"
                :on-preview="handlePreview" :on-success="handleUploadSuccess" :on-remove="handleRemove"
                :headers="headers" :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed"
                :file-list="fileList" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" class="add" @click="submitForm">{{
          addForm.id ? "确认编辑" : "确认添加"
          }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getSetList,
    removeSet,
    getSystem,
    updateSystem,
    addSet,
    editSet,
    getSetById,
  } from "@/api/index";
  import { getToken } from "@/utils/auth";
  export default {
    name: "Role",
    dicts: ["sys_setting_state"],
    data() {
      return {
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadPc/busConfig", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],
        title: "新增",
        open: false,
        tableKey: 0,
        activeName: "first",
        statusList: [
          {
            value: 1,
            label: "开启",
          },
          {
            value: 0,
            label: "关闭",
          },
        ],
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 10,
        // 角色表格数据
        roleList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        addForm: {
          title: "",
          content: "",
          pageUrl: "",
          status: "1",
          tag: "",
          imgUrl: "",
        },
        addRules: {
          title: [{ required: true, message: "内容不能为空", trigger: "blur" }],
          content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
          pageUrl: [{ required: true, message: "内容不能为空", trigger: "blur" }],
          tag: [{ required: true, message: "内容不能为空", trigger: "blur" }],
        },
        systemList: [],
        input: '',
        ocrList:[],
      };
    },
    created() {
      this.getSystemData();
    },
    methods: {
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
        const isJPG = type.includes(file.type);
        // 检验文件格式
        if (!isJPG) {
          this.$message.error(`图片格式错误!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 < 500;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 500 KB!`);
            return false;
          }
        }
        return true;
      },
      handleRemove(file, fileList) {
        this.form.imgUrl = "";
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
          } 个文件`
        );
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleUploadSuccess(res, file) {
        // 如果上传成功
        if (res.code == 200) {
          this.addForm.imgUrl = res.fileName;
        } else {
          this.$message.error("图片上传失败");
        }
      },
      handleClick(tab, event) {
        if (this.activeName == "second") {
          this.resetQuery();
          this.tableKey += 1;
        }
        if (this.activeName == "ocr") {
          getSystem({ configType: 2 }).then((res) => {
            this.ocrList = res.data;
          });
        }
      },
      getSystemData() {
        getSystem({}).then((res) => {
          this.systemList = res.data;
        });
      },
      updateSystemData() {
        updateSystem(this.systemList).then(() => {
          this.$modal.msgSuccess("修改成功");
        });
      },
      // ocr提交
      updateOcrData(){
        updateSystem(this.ocrList).then(() => {
          this.$modal.msgSuccess("修改成功");
        });
      },
      /** 查询角色列表 */
      getListData() {
        this.loading = true;
        getSetList({ ...this.queryParams }).then((response) => {
          this.roleList = response.data.records;
          this.total = response.data.total || 0;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$nextTick(() => {
          this.getListData();
        });
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.pageNum = 1;
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.title = "新增";
        this.open = true;
        this.reset();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.title = "编辑";
        console.log(row);
        getSetById(row.id).then((res) => {
          this.addForm.id = row.id;
          this.addForm.title = res.data.title;
          this.addForm.tag = res.data.tag;
          this.addForm.status = res.data.status.toString();
          this.addForm.content = res.data.content;
          this.addForm.pageUrl = res.data.pageUrl;
          this.addForm.imgUrl = res.data.imgUrl;
          this.fileList = [
            {
              name: res.data.imgUrl.split("/").pop(),
              url: "/api" + res.data.imgUrl,
            },
          ];
          this.open = true;
        });
      },
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.addForm = {
          title: "",
          content: "",
          pageUrl: "",
          status: "1",
          tag: "",
          imgUrl: "",
        };
        this.fileList = [];
        this.resetForm("addForm");
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const roleIds = row.id;
        this.$modal
          .confirm("是否确认删除数据？")
          .then(function () {
            return removeSet(roleIds);
          })
          .then(() => {
            this.getListData();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => { });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["addForm"].validate((valid) => {
          if (valid) {
            if (!this.addForm.imgUrl) return this.$message.error("请上传图片");
            if (this.addForm.id) {
              editSet({ ...this.addForm }).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getListData();
              });
            } else {
              addSet({ ...this.addForm }).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getListData();
              });
            }
          }
        });
      },
    },
  };
</script>
<style lang="scss" scoped>
  .footerForm {
    margin-left: 200px;
  }

  .formBox {
    width: 600px;
    margin-top: 40px;
  }

  .btnText {
    color: #0052d9 !important;
  }

  .dialogForm {
    ::v-deep .el-form-item {
      margin-bottom: 10px;
    }

    ::v-deep.el-form--label-top .el-form-item__label {
      padding: 0;
    }
  }

  .add {
    background: #0052d9;
    color: #fff;
    border: none;
  }

  .delBtn {
    background: #e7e7e7;
    color: #000;
    border: none;
  }

  .open {
    width: 52px;
    height: 32px;
    background: #e3f9e9;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #2ba471;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #2ba471;
  }

  .close {
    width: 52px;
    height: 32px;
    background: #d8d8d8;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #767676;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #767676;
  }

  .statusBox {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .img {
    width: 38px;
    height: 38px;
  }

  .ocrBox {
    margin-top: 40px;
  }

  .item-box {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .left {
      width: 200px;
      text-align: right;
      font-size: 14px;
      color: #606266;
      font-weight: 700;
    }

    .right {
      flex: 1;
      margin-left: 80px;

      .ipt {
        width: 400px;
      }
    }
  }
</style>